<template>
    <div class="group-container">
        <div class="action-bar">
            <el-button @click="open(null)" type="primary" size="small" icon="Plus">
                新增
            </el-button>

        </div>


        <el-table :data="tableData.list" stripe style="width: 100%">
            <el-table-column label="id" prop="id" />
            <el-table-column label="昵称" prop="name" />
            <el-table-column label="菜单权限" prop="permissionName" width="500px" />
            <el-table-column label="操作">
                <template #default="scope">
                    <el-button type="primary" @click="open(scope.row)">编辑</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 内容分页 -->
        <div class="pagination-info">
            <el-pagination v-model:current-page="paginationData.pageNum" size="small" :background="false"
                layout="total, prev, pager, next" :total="tableData.total" @current-change="handleCurrentChange" />
        </div>




        <el-dialog v-model="dialogVisible" title="Tips" width="500" :before-close="handleClose">
            <el-form ref="formRef" :model="form" :rules="rules">
                <el-form-item v-show="false">
                    <el-input v-model="form.id">

                    </el-input>
                </el-form-item>
                <el-form-item label="名称" prop="name">
                    <el-input v-model="form.name" placeholder="请填写权限名称" />
                </el-form-item>
                <el-form-item label="权限">
                    <!-- 通过ref拿到el-tree这个组件的实例 -->
                    <!-- id是menuData里的 -->
                    <el-tree ref="treeRef" style="max-width: 600px" :data="menuData" show-checkbox
                        :default-expanded-keys="[2]" node-key="id" :default-checked-keys="defaultKeys" />
                </el-form-item>
            </el-form>

            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="confirm(formRef)">确认</el-button>
                </div>
            </template>
        </el-dialog>

    </div>


</template>
<script setup>
import { ElMessage } from 'element-plus'
import { ref, onMounted, reactive, nextTick } from 'vue'
import { getMenus, setMenus, menuList } from '../../../api'

// 列表数据
const tableData = reactive({
    list: [],
    total: 0
})


// 请求参数
const paginationData = reactive({
    pageNum: 1,
    pageSize: 10
})

// el-tree实例
const treeRef = ref()
// 表单实例
const formRef = ref()
// 表单数据
const form = reactive({
    id: '',
    name: '',
    permissions: ''
})



const defaultKeys = [4, 5]

// 树形菜单权限数据
const permissionsData = ref([])

const menuData = ref([])


// 请求列表数据
const getListData = () => {
    menuList(paginationData).then(({ data }) => {
        const { list, total } = data.data
        tableData.list = list
        tableData.total = total
    })
}


// 组件加载时执行该内容 
onMounted(() => {
    getListData()
    console.log('menuList', tableData);


    getMenus().then((data) => {
        console.log(data.data.data, 'dataMenu');
        menuData.value = data.data.data

    })

})

// 关闭菜单的回调
const handleClose = () => {
    dialogVisible.value = false
    formRef.value.resetFields()
    // 修复了点击编辑直接新增导致编辑原有项的问题
    Object.assign(form, { id: '' })
    treeRef.value.setCheckedKeys(defaultKeys)
}


// el-form的校验规则
const rules = reactive({
    name: [
        { required: true, trigger: 'blur', message: "请输入权限名称" },
        // { validator: validatePermissionName, trigger: 'blur' }
    ]
})


// 弹窗的显示与隐藏
const dialogVisible = ref(false)
const open = (rowData = {}) => {
    dialogVisible.value = true;
    nextTick(() => {
        // 如果是编辑
        // 编辑有问题
        if (rowData) {
            // 直接form=reactive({...})会导致失去响应式，所以使用Object.assign
            Object.assign(form, { id: rowData.id, authName: rowData.name })
            console.log(`当前正在编辑id为:${form.id}的内容`, form);
            // 
            treeRef.value.setCheckedKeys(rowData.permission)
        }
    })
}


// 表单提交
const confirm = async (formEl) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {

            setMenus({ id: form.id, name: form.name, permissions: JSON.stringify(treeRef.value.getCheckedKeys()) }).then(() => {
                handleClose()
                getListData()
            })

        } else {
            console.log('error', fields);

        }
    })
}


// 分页切换的回调
const handleCurrentChange = (val) => {
    // val是pagination的页码
    paginationData.pageNum = val
    // 修改页码后更新内容
    getListData()
}




// 定义允许的权限名称范围
const allowedPermissions = ['权限1', '权限2']
// 自定义验证函数
const validatePermissionName = (rule, value, callback) => {
    if (allowedPermissions.includes(value)) {
        callback() // 验证通过
    } else {
        callback(new Error('请输入正确的权限名称，可选值为：' + allowedPermissions.join(', ')))
    }
}





</script>
<style lang="less" scoped>
.group-container {
    padding: 20px;
    background: #f5f7fa;
    min-height: calc(100vh - 60px);
}

.action-bar {
    margin-bottom: 20px;
    padding: 12px 16px;
    background: white;
    border-radius: 4px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
}
</style>